<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
namespace app\api\controller\wddj;

use app\admin\model\wddj\InvoiceConfig;
use app\api\model\wddj\LookUp;
use app\api\model\wddj\User;
use app\api\model\wddj\user\Order;
use app\common\controller\Api;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 发票管理
 */
class Invoice extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];


    protected $model = null;
    protected $wechat_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\wddj\Invoice();
        $this->wechat_id = User::getWechatId($this->auth->id);
        if (empty($this->wechat_id)) {
            $this->error('用户信息不存在');
        }
    }

    /**
     * Desc  提交审核
     * Create on 2024/10/12 10:08
     * Create by @小趴菜
     */
    public function apply_for_invoice()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->post();
        if (empty($param['order_id']) || empty($param['title_id'])) {
            $this->error('参数错误');
        }
        $lookUpObj = (new LookUp())->where('id',$param['title_id'])
            ->where('wechat_id',$this->wechat_id)
            ->find();
        if (!$lookUpObj) {
            $this->error('抬头不存在');
        }

        $order_id_array = explode(',',$param['order_id']);
        $update_order_data = array();

        $where['wechat_id'] = array('eq',$this->wechat_id);
        $where['state'] = array('eq','completed');
        $where['invoice_status'] = array('<>',1);
        foreach ($order_id_array as $v) {
            $where_query[] = ['exp',Db::raw("FIND_IN_SET($v,order_id)")];
            $row = $this->model->where($where_query)->where('wechat_id',$this->wechat_id)->find();
            if ($row) {
                $this->error('已提交发票申请');
            }
            unset($where_query);
            $orderObj = (new Order())
                ->where('id',$v)
                ->where($where)
                ->find();
            if (!$orderObj) {
                $this->error('没有查到订单，无法开具发票');
            }

            $update_order_data[] = array(
                'id'=>$v,
                'invoice_status'=>1,
            );
        }

        $param['wechat_id'] = $this->wechat_id;
        $param['createtime'] = time();
        $orderModel = new Order();
        $result = false;
        Db::startTrans();
        try {
            $this->model->data($param);
            $result = $this->model->allowField(true)->save();
            $orderModel->saveAll($update_order_data);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if(false === $result){
            $this->error($this->model->getError());
        }
        $this->success('提交成功');
    }

    /**
     * Desc  发票列表
     * Create on 2024/9/03 09:16
     * Create by @小趴菜
     */
    public function list()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->get();
        $page = isset($param['page']) ? $param['page'] : '';
        $limit = isset($param['limit']) ? $param['limit'] : 10;
        $where = [];
        $where['invoice.wechat_id'] = array('eq',$this->wechat_id);
        $count =$this->model
            ->alias('invoice')
            ->where($where)
            ->join('wddj_order order','invoice.order_id = order.id')
            ->join('wddj_look_up look_up','invoice.title_id = look_up.id and invoice.wechat_id = look_up.wechat_id')
            ->where($where)->count();
        $list = $this->model
            ->alias('invoice')
            ->where($where)
            ->join('wddj_order order','invoice.order_id = order.id')
            ->join('wddj_look_up look_up','invoice.title_id = look_up.id and invoice.wechat_id = look_up.wechat_id')
            ->field('look_up.title_type,invoice.status,invoice.file,invoice.order_id,look_up.invoice_type')
            ->order('invoice.id desc')
            ->page($page,$limit)
            ->select();

        $orderModel = new Order();
        foreach ($list as $v) {
            $v->fees = $orderModel->where('id','in',explode(',',$v->order_id))->sum('pay_amount');
            unset($v['order_id']);
        }

        $invoicing_party = (new InvoiceConfig())->where('id',1)->value('invoicing_party');
        $this->success('请求成功',['count' => $count,'data' => $list,'invoicing_party'=>$invoicing_party]);
    }

    /**
     * Desc 金额
     * Create on 2024/10/12 9:03
     * Create by wangyafang
     */
    public function fees()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $order_id = $this->request->get('order_id');
        $orderObj = (new Order())->where('id',$order_id)->where('paid','2')
            ->where('state','5')
            ->field('id')
            ->find();
        if (!$orderObj) {
            $this->error('订单未完成，无法操作');
        }
        $fees = (new Order())->where('id',$order_id)->value('pay_amount');

        $this->success('请求成功',['fees'=>$fees]);
    }
}
